package com.hwz.gulimall.product.exception;

import com.hwz.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.stream.Collectors;

/**
 * @Author: hwz
 * @CreateTime: 2025-06-02
 */

@RestControllerAdvice(basePackages = "com.hwz.gulimall.product.controller")
@Slf4j
public class ControllerExceptionHandler {

    // 处理参数校验异常
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public R handleValidationException(MethodArgumentNotValidException ex) {
            log.error("参数校验错误");

        HashMap<String, String> errMap = new HashMap<>();
        BindingResult bindingResult = ex.getBindingResult();
        bindingResult.getFieldErrors()
                .forEach( fieldError -> errMap.put(fieldError.getField(), fieldError.getDefaultMessage()));
        return R.error(400, "参数校验错误").put("data",errMap);
    }

    @ExceptionHandler(Exception.class)
    public R handleException(Exception ex) {
        log.error("未知错误");
        return R.error(400, "参数校验错误").put("data",ex.getMessage());
    }


}
